package webdemo;

import java.io.File;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class SimpleSocketServer extends Thread{ 
	private SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd");
	private NewLevel2HandlerConcat level2_handler = new NewLevel2HandlerConcat();
	private DatagramSocket dataGramSocket = null;
    /**
     * Constructor
     * @param port port used to listen incoming connection
     * @throws SocketException error to consturct a DatagramSocket with this port
     */
    public SimpleSocketServer(int port) throws SocketException{
        this("MediatorServerThread", port);
    }
    
    /**
     * Constructor
     * @param name the thread name
     * @param port port used to listen incoming connection
     * @throws SocketException error to consturct a DatagramSocket with this port
     */
    public SimpleSocketServer(String name, int port) throws SocketException{
        super(name);
        dataGramSocket = new DatagramSocket(port);
		File file = new File("./data");
		if(file.exists() == false){
			file.mkdir();
		}
		level2_handler.start("./data/"+df.format(new Date()));
        dataGramSocket.setReceiveBufferSize(dataGramSocket.getReceiveBufferSize() * 2); 
        System.out.println("Mediator server started on JDK model...");
        System.out.println("Socket buffer size: " + dataGramSocket.getReceiveBufferSize());
    }
    
    public void run(){
        long startTime = 0;
        byte[] buf = null;
        while(true){
            try {
                buf = new byte[1024];
                // receive request
                DatagramPacket dataGramPacket = new DatagramPacket(buf, buf.length);
                dataGramSocket.receive(dataGramPacket); 
                level2_handler.doMsg(new String(buf));
            }catch (IOException e) {
            	e.printStackTrace();
            }
            }
        }
    
    public static void main(String[] args) {
    	SimpleSocketServer socket;
		try {
			socket = new SimpleSocketServer(60001);
	    	socket.start();
		} catch (SocketException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}
    }
   
